'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Search, Plus, Edit, Trash2, AlertCircle } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Switch } from '@/components/ui/switch';

interface IllegalWord {
  id: number;
  words: string | null;
  isEnable: number | null;
  createDate: string | null;
}

export default function IllegalWordsPage() {
  const [illegalWords, setIllegalWords] = useState<IllegalWord[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [wordToDelete, setWordToDelete] = useState<number | null>(null);
  const [newWord, setNewWord] = useState({
    words: '',
    isEnable: 1
  });
  const [editWord, setEditWord] = useState<IllegalWord | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);

  useEffect(() => {
    fetchIllegalWords();
  }, []);

  const fetchIllegalWords = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/illegal-words');
      
      if (!response.ok) {
        throw new Error('获取敏感词数据失败');
      }
      
      const data = await response.json();
      setIllegalWords(data.illegalWords);
    } catch (error) {
      console.error('获取敏感词数据失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateWord = async () => {
    try {
      if (!newWord.words) {
        alert('敏感词内容不能为空');
        return;
      }

      const response = await fetch('/api/illegal-words', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newWord),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '创建敏感词失败');
      }

      // 重置表单并关闭对话框
      setNewWord({
        words: '',
        isEnable: 1
      });
      setIsDialogOpen(false);
      
      // 重新获取敏感词列表
      fetchIllegalWords();
    } catch (error) {
      console.error('创建敏感词失败:', error);
      alert(error instanceof Error ? error.message : '创建敏感词失败');
    }
  };

  const handleUpdateWordStatus = async (id: number, isEnable: number) => {
    try {
      const response = await fetch('/api/illegal-words', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id,
          isEnable: isEnable === 1 ? 0 : 1 // 切换状态
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '更新敏感词状态失败');
      }

      // 重新获取敏感词列表
      fetchIllegalWords();
    } catch (error) {
      console.error('更新敏感词状态失败:', error);
      alert(error instanceof Error ? error.message : '更新敏感词状态失败');
    }
  };

  const handleDeleteWord = async (id: number) => {
    setWordToDelete(id);
    setIsDeleteDialogOpen(true);
  };

  const confirmDeleteWord = async () => {
    if (!wordToDelete) return;
    
    try {
      const response = await fetch(`/api/illegal-words?id=${wordToDelete}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '删除敏感词失败');
      }

      // 关闭对话框并重新获取敏感词列表
      setIsDeleteDialogOpen(false);
      setWordToDelete(null);
      fetchIllegalWords();
    } catch (error) {
      console.error('删除敏感词失败:', error);
      alert(error instanceof Error ? error.message : '删除敏感词失败');
    }
  };

  // 格式化日期
  const formatDate = (dateString: string | null) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  // 过滤敏感词
  const filteredWords = illegalWords.filter(word => 
    word.words?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">敏感词管理</h1>
        <p className="text-muted-foreground">查看和管理系统敏感词信息</p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">敏感词列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索敏感词..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogTrigger asChild>
                <Button>
                  <Plus className="mr-2 h-4 w-4" />
                  添加敏感词
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>添加新敏感词</DialogTitle>
                  <DialogDescription>
                    请填写以下信息创建新的敏感词
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="words" className="text-right">
                      敏感词内容
                    </Label>
                    <Input
                      id="words"
                      value={newWord.words}
                      onChange={(e) => setNewWord({...newWord, words: e.target.value})}
                      className="col-span-3"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="isEnable" className="text-right">
                      是否启用
                    </Label>
                    <div className="flex items-center space-x-2 col-span-3">
                      <Switch
                        id="isEnable"
                        checked={newWord.isEnable === 1}
                        onCheckedChange={(checked) => setNewWord({...newWord, isEnable: checked ? 1 : 0})}
                      />
                      <Label htmlFor="isEnable">{newWord.isEnable === 1 ? '启用' : '禁用'}</Label>
                    </div>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsDialogOpen(false)}>取消</Button>
                  <Button onClick={handleCreateWord}>创建</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>敏感词内容</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredWords.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center h-24">未找到匹配的敏感词</TableCell>
                  </TableRow>
                ) : (
                  filteredWords.map((word) => (
                    <TableRow key={word.id}>
                      <TableCell>{word.id}</TableCell>
                      <TableCell className="font-medium">{word.words || '-'}</TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Switch
                            checked={word.isEnable === 1}
                            onCheckedChange={() => handleUpdateWordStatus(word.id, word.isEnable || 0)}
                          />
                          <Badge variant={word.isEnable === 1 ? "success" : "destructive"}>
                            {word.isEnable === 1 ? '启用' : '禁用'}
                          </Badge>
                        </div>
                      </TableCell>
                      <TableCell>{formatDate(word.createDate)}</TableCell>
                      <TableCell className="text-right">
                        <Button 
                          variant="ghost" 
                          size="icon"
                          onClick={() => handleDeleteWord(word.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 删除确认对话框 */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除这个敏感词吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setWordToDelete(null)}>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDeleteWord}>确认删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}